package com.itheima.mp.Controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mp.Service.UserService;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @description:
 * @author: 韩汶锦
 * @date: 2025/4/9
 */
@RestController
@Slf4j
@RequestMapping("/user")
@RequiredArgsConstructor
@Api(tags = "用户管理接口")
public class UserController {

    private final UserService userService;

    @PutMapping
    @ApiOperation("新增用户")
    public void  save(@RequestBody UserFormDTO user){
        User user1 = BeanUtil.copyProperties(user, User.class);
        userService.save(user1);

    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public void  delete(@PathVariable("id") Long id){
        userService.removeById(id);
    }

    @GetMapping("/{id}")
    @ApiOperation("查询用户")
    public UserVO get(@PathVariable("id") Long id){
        return userService.queryUserAndAddresses(id);
    }

    @GetMapping
    @ApiOperation("根据id集合查询")
    public List<UserVO> list(@RequestParam("ids") List<Long> ids){

        return userService.queryUserAndAddressesByIds(ids);
    }

    @PutMapping("{id}/deduction/{money}")
    @ApiOperation("扣减用户余额")
    public void deduction(@PathVariable("id") Long id,@PathVariable("money") Integer money){
        userService.deduction(id,money);
    }
    @GetMapping("/list")
    @ApiOperation("根据id集合查询用户")
    public List<UserVO> queryUsers(UserQuery query){

        Integer maxBalance = query.getMaxBalance();
        Integer minBalance = query.getMinBalance();
        String name = query.getName();
        Integer status = query.getStatus();

/*        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .like(name!=null,User::getUsername,name)
                .eq(status!= null,User::getStatus,status)
                .between ( minBalance!= null && maxBalance != null, User::getBalance,minBalance,maxBalance);
        List<User> list = userService.list(wrapper);*/

        List<User> list = userService.lambdaQuery()
                .like(name!=null,User::getUsername,name)
                .eq(status!= null,User::getStatus,status)
                .between ( minBalance!= null && maxBalance != null, User::getBalance,minBalance,maxBalance)
                .list();
        return BeanUtil.copyToList(list,UserVO.class);

    }

    @GetMapping("/page")
    public PageDTO<UserVO> queryUsersPage(UserQuery query){
        return userService.queryUsersPage(query);
    }

}
